package com.feityz.provider;

import antlr.actions.python.CodeLexer;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessDefinition;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.model.task.Task;
import com.bstek.uflo.model.variable.Variable;
import com.bstek.uflo.process.assign.AssigneeProvider;
import com.bstek.uflo.process.assign.Entity;
import com.bstek.uflo.process.assign.PageQuery;
import com.feityz.system.entity.*;
import com.feityz.system.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class RoleDeptAssigneeProvider implements AssigneeProvider {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUserAndRoleService userAndRoleService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleDeptService roleDeptService;
    @Autowired
    private IRoleDeptUserService roleDeptUserService;
    @Override
    public boolean isTree() {
        return false;
    }

    @Override
    public String getName() {
        return "按部门角色(请在流程变量中传入[DEPT]参数";
    }

    @Override
    public void queryEntities(PageQuery<Entity> pageQuery, String parentId) {
        IPage<Role> page = new Page<>(pageQuery.getPageIndex(),pageQuery.getPageSize());
        page = roleService.page(page);
        List<Role> depts = page.getRecords();
        List<Entity> entities = new ArrayList<>();
        depts.forEach(n->{
            Entity en = new Entity(n.getId().toString(),n.getRoleName());
            entities.add(en);
        });
        pageQuery.setResult(entities);
        pageQuery.setRecordCount((int)page.getTotal());
    }

    /**
     * 按角色取人员
     * @param entityId 处理人ID，可能是一个用户的用户名，这样就是直接返回这个用户名，也可能是一个部门的ID，那么就是返回这个部门下的所有用户的用户名等
     * @param context context 流程上下文对象
     * @param processInstance 流程实例对象
     * @return
     */
    @Override
    public Collection<String> getUsers(String entityId, Context context, ProcessInstance processInstance) {
        List<String> users = new ArrayList<>();

        List<Variable> areas = context.getProcessService().createProcessVariableQuery().processInstanceId(processInstance.getId()).key("DEPT").list();

        Assert.isTrue(CollectionUtil.isNotEmpty(areas),"DEPT");

        String[] deptCode = areas.get(0).getValue().toString().split(",");

        List<RoleDept> roleDepts = new ArrayList<>();
        for (String s : deptCode) {
            List<RoleDept> roleDept = roleDeptService.lambdaQuery().like(RoleDept::getDeptNum, s)
                    .eq(RoleDept::getRoleId,entityId)
                    .list();
            roleDepts.addAll(roleDept);
        }
        if(CollectionUtil.isNotEmpty(roleDepts)){
            List<Long> roleDeptIds = roleDepts.stream().map(e->e.getId()).collect(Collectors.toList());;
            List<RoleDeptUser> roleDeptUsers = roleDeptUserService.lambdaQuery().in(RoleDeptUser::getRoleDeptId, roleDeptIds)
                    .list();
            if(CollectionUtil.isNotEmpty(roleDeptUsers)){
                users =  roleDeptUsers.stream().map(e->e.getUserId().toString()).collect(Collectors.toList());
            }
        }
        ProcessDefinition process = context.getProcessService().getProcessById(processInstance.getProcessId());
        String key = process.getKey();
        /*if("OPSCPTW".equals(key)){
            //签发和签收不能是同一个人
            List<Task> qianfaTasks = context.getTaskService().createTaskQuery()
                    .businessId(processInstance.getBusinessId())
                    .nodeName("辖区PTW签发者")
                    .list();

            if(CollectionUtil.isNotEmpty(qianfaTasks)){

                List<String> qianfaUsers = qianfaTasks.stream().map(e -> e.getAssignee()).collect(Collectors.toList());

                users = users.stream()
                        .filter(e -> !qianfaUsers.contains(e.toString())).collect(Collectors.toList());
            }
        }*/

        return users;
    }

    @Override
    public boolean disable() {
        return false;
    }
}
